import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Button, Selector, Space, Tag } from "antd-mobile";
import { OpsBlock } from "@components";
import { createAction } from "@common/utils";
import {
  SAGA_DATA_SYNC_LOAD_ITEMS,
  SAGA_DATA_SYNC_DOWNLOAD,
  SAGA_DATA_SYNC_CLEAR,
} from "@store/data-sync/saga-types";

const DataSync = () => {
  const dispatch = useDispatch();
  const [selectedItems, setSelectedItems] = useState([]);
  const dataSyncItems = useSelector((state) => state.dataSync.items);

  useEffect(() => {
    dispatch(createAction(SAGA_DATA_SYNC_LOAD_ITEMS));
  }, []);

  const handleSelect = (arr) => {
    setSelectedItems(arr);
  };

  const handleDownload = () => {
    let payload = { items: [...selectedItems] };
    if (selectedItems.length === 0) {
      payload = { items: dataSyncItems.map((i) => i.code) };
    }
    dispatch(createAction(SAGA_DATA_SYNC_DOWNLOAD, payload));
  };

  const handleClear = () => {
    let payload = [...selectedItems];
    if (selectedItems.length === 0) {
      payload = dataSyncItems.map((i) => i.code);
    }
    dispatch(createAction(SAGA_DATA_SYNC_CLEAR, payload));
  };

  return (
    <>
      <OpsBlock gap={16} columns={2} title="数据同步" icon="yunduantongbu">
        <Selector
          columns={2}
          multiple={true}
          onChange={handleSelect}
          options={dataSyncItems.map((i) => ({
            label: (
              <div>
                <span style={{ marginRight: "0.5rem" }}>{i.displayTxt}</span>
                <Tag
                  round
                  color="primary"
                  style={{ fontSize: 15, padding: "1px 4px" }}
                >
                  {i.qty}
                </Tag>
              </div>
            ),
            description: i.lastSyncAt,
            value: i.code,
          }))}
        />
      </OpsBlock>
      <div style={{ textAlign: "center", marginBottom: "0.75rem" }}>
        <Space>
          <Button
            color="primary"
            onClick={handleDownload}
            disabled={dataSyncItems.length === 0}
          >{`${selectedItems.length > 0 ? "" : "全部"}下载`}</Button>
          <Button
            color="danger"
            onClick={handleClear}
            disabled={dataSyncItems.length === 0}
          >{`${selectedItems.length > 0 ? "" : "全部"}清理`}</Button>
        </Space>
      </div>
    </>
  );
};

export default DataSync;
